<!-- 复选框父组件 -->
<template>
  <view class="w-components-container w-checkbox-group">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { useCheckbox } from '@/common/use/checkbox';
import { ICheckboxTransmit, PrimaryKey } from '@/types';
import { provide, reactive, ref, watch, watchEffect } from 'vue';
// typescript
type TShape = 'circle' | 'square';

interface IProps {
  /**
   * value v-model
   */
  value: PrimaryKey[]

  /**
   * 最大可选数，0 为无限制
   */
  max?: number

  /**
   * 使用 单选框模式
   * max 参数将失效
   */
  radio?: boolean
}

interface IEmits {
  (e: 'update:value', value: PrimaryKey[]): void
  (e: 'change', value: PrimaryKey[]): void
}

const emits = defineEmits<IEmits>();
const props = withDefaults(defineProps<IProps>(), {
  value: () => [],
  max: 0,
  radio: false
});
const { getKey } = useCheckbox();
const transmit = reactive<ICheckboxTransmit>({
  checkbox: props.value as PrimaryKey[],
  max: props.max,
  radio: props.radio,
  items: []
});
// 提供数据
const parentProvide = provide(getKey(), transmit);
// 全选
const selectAll = () => {
  transmit.checkbox = transmit.items.map(x => x.value);
}
// 反选
const invertSelection = () => {

}
// 清除全部
const clearAll = () => {
  transmit.checkbox = [];
}

// 导出公开方法
defineExpose({
  selectAll,
  invertSelection,
  clearAll
});

watch(transmit.checkbox, () => {
  emits('update:value', transmit.checkbox);
  emits('change', transmit.checkbox);
});

watch(() => props.value, () => {
  transmit.checkbox = props.value;
});
</script>

<style scoped lang="scss">
// scss
</style>